{% extends 'base.html' %}
{% load static %}

{% block title %}个人中心 - 商城系统{% endblock %}

{% block extra_css %}
<style>
    .profile-sidebar {
        background-color: #f8f9fa;
        border-radius: 5px;
        padding: 20px;
    }
    
    .profile-avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        object-fit: cover;
        margin-bottom: 15px;
    }
    
    .profile-username {
        font-size: 1.2rem;
        font-weight: 600;
        margin-bottom: 5px;
    }
    
    .nav-pills .nav-link.active {
        background-color: #0d6efd;
    }
    
    .profile-content {
        background-color: #fff;
        border-radius: 5px;
        padding: 25px;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
    
    .address-card {
        border: 1px solid #e0e0e0;
        border-radius: 5px;
        padding: 15px;
        margin-bottom: 15px;
        position: relative;
    }
    
    .address-card.default {
        border-color: #0d6efd;
    }
    
    .address-default-badge {
        position: absolute;
        top: 10px;
        right: 10px;
        background-color: #0d6efd;
        color: white;
        padding: 2px 8px;
        border-radius: 10px;
        font-size: 12px;
    }
    
    .address-card-actions {
        margin-top: 10px;
    }
    
    #addressModal .modal-body {
        padding: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container py-5">
    <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-3 mb-4">
            <div class="profile-sidebar">
                <!-- 用户头像和名称 -->
                <div class="text-center mb-4">
                    {% if user.profile.avatar %}
                    <img src="{{ user.profile.avatar.url }}" alt="{{ user.username }}" class="profile-avatar">
                    {% else %}
                    <img src="{% static 'img/default-avatar.png' %}" alt="{{ user.username }}" class="profile-avatar">
                    {% endif %}
                    <h5 class="profile-username">{{ user.username }}</h5>
                    {% if user.profile.email_verified %}
                    <span class="badge bg-success"><i class="bi bi-check-circle-fill"></i> 已验证</span>
                    {% else %}
                    <span class="badge bg-warning"><i class="bi bi-exclamation-circle-fill"></i> 未验证</span>
                    {% endif %}
                </div>
                
                <!-- 菜单 -->
                <div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">
                    <button class="nav-link active" id="profile-info-tab" data-bs-toggle="pill" data-bs-target="#profile-info" type="button" role="tab" aria-controls="profile-info" aria-selected="true">个人资料</button>
                    <button class="nav-link" id="address-tab" data-bs-toggle="pill" data-bs-target="#address" type="button" role="tab" aria-controls="address" aria-selected="false">收货地址</button>
                    <button class="nav-link" id="orders-tab" data-bs-toggle="pill" data-bs-target="#orders" type="button" role="tab" aria-controls="orders" aria-selected="false">我的订单</button>
                    <button class="nav-link" id="security-tab" data-bs-toggle="pill" data-bs-target="#security" type="button" role="tab" aria-controls="security" aria-selected="false">账号安全</button>
                </div>
            </div>
        </div>
        
        <!-- 主要内容 -->
        <div class="col-md-9">
            <div class="profile-content">
                <div class="tab-content" id="v-pills-tabContent">
                    <!-- 个人资料 -->
                    <div class="tab-pane fade show active" id="profile-info" role="tabpanel" aria-labelledby="profile-info-tab">
                        <h3 class="mb-4">个人资料</h3>
                        <form method="post" enctype="multipart/form-data">
                            {% csrf_token %}
                            
                            <!-- 头像上传 -->
                            <div class="mb-3">
                                <label for="{{ form.avatar.id_for_label }}" class="form-label">头像</label>
                                <div class="d-flex align-items-center">
                                    <div class="me-3">
                                        {% if user.profile.avatar %}
                                        <img src="{{ user.profile.avatar.url }}" alt="当前头像" width="80" height="80" class="rounded-circle">
                                        {% else %}
                                        <img src="{% static 'img/default-avatar.png' %}" alt="默认头像" width="80" height="80" class="rounded-circle">
                                        {% endif %}
                                    </div>
                                    <div>
                                        {{ form.avatar }}
                                        {% if form.avatar.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.avatar.errors }}
                                        </div>
                                        {% endif %}
                                        <small class="text-muted">支持JPG、PNG格式，文件小于2MB</small>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <!-- 用户名 -->
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">用户名</label>
                                    <input type="text" class="form-control" value="{{ user.username }}" disabled>
                                    <small class="text-muted">用户名不可修改</small>
                                </div>
                                
                                <!-- 邮箱 -->
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">邮箱</label>
                                    <input type="email" class="form-control" value="{{ user.email }}" disabled>
                                    <small class="text-muted">邮箱不可修改</small>
                                </div>
                            </div>
                            
                            <div class="row">
                                <!-- 性别 -->
                                <div class="col-md-6 mb-3">
                                    <label for="{{ form.gender.id_for_label }}" class="form-label">性别</label>
                                    {{ form.gender }}
                                    {% if form.gender.errors %}
                                    <div class="invalid-feedback d-block">
                                        {{ form.gender.errors }}
                                    </div>
                                    {% endif %}
                                </div>
                                
                                <!-- 生日 -->
                                <div class="col-md-6 mb-3">
                                    <label for="{{ form.birthday.id_for_label }}" class="form-label">生日</label>
                                    {{ form.birthday }}
                                    {% if form.birthday.errors %}
                                    <div class="invalid-feedback d-block">
                                        {{ form.birthday.errors }}
                                    </div>
                                    {% endif %}
                                </div>
                            </div>
                            
                            <!-- 手机号 -->
                            
                            
                            <!-- 个人简介 -->
                            <div class="mb-4">
                                <label for="{{ form.bio.id_for_label }}" class="form-label">个人简介</label>
                                {{ form.bio }}
                                {% if form.bio.errors %}
                                <div class="invalid-feedback d-block">
                                    {{ form.bio.errors }}
                                </div>
                                {% endif %}
                            </div>
                            
                            <!-- 提交按钮 -->
                            <div class="text-end">
                                <button type="submit" class="btn btn-primary px-4">保存资料</button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- 收货地址 -->
                    <div class="tab-pane fade" id="address" role="tabpanel" aria-labelledby="address-tab">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h3>收货地址</h3>
                            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addressModal">
                                <i class="bi bi-plus-circle"></i> 新增地址
                            </button>
                        </div>
                        
                        {% if addresses %}
                            <div class="address-list">
                                {% for address in addresses %}
                                <div class="address-card {% if address.is_default %}default{% endif %}">
                                    {% if address.is_default %}
                                    <span class="address-default-badge">默认地址</span>
                                    {% endif %}
                                    
                                    <div class="address-info">
                                        <h6>{{ address.receiver }} <span class="badge bg-light text-dark">{{ address.phone }}</span></h6>
                                        <p class="mb-1">{{ address.province }} {{ address.city }} {{ address.district }} {% if address.street %}{{ address.street }}{% endif %}</p>
                                        <p class="mb-1">{{ address.address }}</p>
                                        {% if address.zip_code %}
                                        <p class="mb-0 text-muted small">邮编：{{ address.zip_code }}</p>
                                        {% endif %}
                                    </div>
                                    
                                    <div class="address-card-actions">
                                        <button class="btn btn-sm btn-outline-primary edit-address" data-address-id="{{ address.id }}">
                                            <i class="bi bi-pencil"></i> 编辑
                                        </button>
                                        {% if not address.is_default %}
                                        <button class="btn btn-sm btn-outline-success set-default-address" data-address-id="{{ address.id }}">
                                            设为默认
                                        </button>
                                        {% endif %}
                                        <button class="btn btn-sm btn-outline-danger delete-address" data-address-id="{{ address.id }}">
                                            <i class="bi bi-trash"></i> 删除
                                        </button>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                        {% else %}
                            <div class="text-center py-4">
                                <i class="bi bi-geo-alt" style="font-size: 3rem;"></i>
                                <p class="mt-3">您还没有添加收货地址</p>
                                <button class="btn btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#addressModal">
                                    <i class="bi bi-plus-circle"></i> 新增地址
                                </button>
                            </div>
                        {% endif %}
                    </div>
                    
                    <!-- 我的订单 -->
                    <div class="tab-pane fade" id="orders" role="tabpanel" aria-labelledby="orders-tab">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h3>我的订单</h3>
                            <a href="{% url 'order_list' %}" class="btn btn-outline-primary">
                                <i class="bi bi-list"></i> 查看全部订单
                            </a>
                        </div>
                        
                        {% if recent_orders %}
                            <div class="orders-list">
                                {% for order in recent_orders %}
                                <div class="card mb-3">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <div>
                                            <span class="fw-bold">订单号：{{ order.order_id }}</span>
                                            <span class="text-muted mx-3">{{ order.created_time|date:"Y-m-d H:i" }}</span>
                                        </div>
                                        <span class="badge bg-{{ order.order_status_display_color }}">
                                            {{ order.get_order_status_display }}
                                        </span>
                                    </div>
                                    
                                    <div class="card-body">
                                        {% for item in order.items.all|slice:":2" %}
                                        <div class="d-flex mb-2 {% if not forloop.last %}border-bottom pb-2{% endif %}">
                                            <img src="{{ item.product.get_main_image_url }}" width="60" height="60" class="me-3" alt="{{ item.product.name }}">
                                            <div class="flex-grow-1">
                                                <h6 class="mb-1">{{ item.product.name }}</h6>
                                                <div class="d-flex justify-content-between">
                                                    <span class="text-danger">¥{{ item.price }}</span>
                                                    <span class="text-muted">x{{ item.quantity }}</span>
                                                </div>
                                            </div>
                                        </div>
                                        {% endfor %}
                                        
                                        {% if order.items.count > 2 %}
                                        <div class="text-center text-muted mt-2">
                                            <small>共 {{ order.items.count }} 件商品</small>
                                        </div>
                                        {% endif %}
                                    </div>
                                    
                                    <div class="card-footer d-flex justify-content-between align-items-center">
                                        <div>
                                            总计：<span class="text-danger fw-bold">¥{{ order.actual_amount }}</span>
                                        </div>
                                        <a href="{% url 'order_detail' order_id=order.order_id %}" class="btn btn-sm btn-outline-primary">
                                            查看详情
                                        </a>
                                    </div>
                                </div>
                                {% endfor %}
                                
                                {% if recent_orders|length >= 3 %}
                                <div class="text-center mt-3">
                                    <a href="{% url 'order_list' %}" class="btn btn-link">查看更多订单 <i class="bi bi-arrow-right"></i></a>
                                </div>
                                {% endif %}
                            </div>
                        {% else %}
                            <div class="text-center py-5">
                                <i class="bi bi-inbox" style="font-size: 3rem;"></i>
                                <p class="mt-3 mb-4">您还没有订单记录</p>
                                <a href="{% url 'index' %}" class="btn btn-primary">去购物</a>
                            </div>
                        {% endif %}
                    </div>
                    
                    <!-- 账号安全 -->
                    <div class="tab-pane fade" id="security" role="tabpanel" aria-labelledby="security-tab">
                        <h3 class="mb-4">账号安全</h3>
                        <div class="mb-4">
                            <h5>修改密码</h5>
                            <div class="mt-3">
                                <a href="{% url 'change_password' %}" class="btn btn-outline-primary">修改密码</a>
                            </div>
                        </div>
                        
                        <div>
                            <h5>账号绑定</h5>
                            <div class="mt-3">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <div>
                                        <i class="bi bi-envelope"></i>
                                        <span class="ms-2">邮箱</span>
                                        <span class="ms-2 text-muted">{{ user.email }}</span>
                                    </div>
                                    <span class="badge bg-success">已绑定</span>
                                </div>
                                <!-- <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <i class="bi bi-phone"></i>
                                        <span class="ms-2">手机</span>
                                        <span class="ms-2 text-muted">{{ user.profile.phone|default:"未绑定" }}</span>
                                    </div>
                                    {% if user.profile.phone %}
                                    <span class="badge bg-success">已绑定</span>
                                    {% else %}
                                    <a href="#" class="btn btn-sm btn-outline-primary">绑定</a>
                                    {% endif %}
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 地址表单模态框 -->
<div class="modal fade" id="addressModal" tabindex="-1" aria-labelledby="addressModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addressModalLabel">添加新地址</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addressForm" method="post" action="{% url 'add_address' %}">
                    {% csrf_token %}
                    <input type="hidden" name="address_id" id="address_id" value="">
                    
                    <div class="mb-3">
                        <label for="id_receiver" class="form-label">收货人</label>
                        <input type="text" class="form-control" id="id_receiver" name="receiver" placeholder="请输入收货人姓名" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="id_province" class="form-label">省份</label>
                            <select class="form-select" id="id_province" name="province" required>
                                <option value="">请选择省份</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="id_city" class="form-label">城市</label>
                            <select class="form-select" id="id_city" name="city" required>
                                <option value="">请选择城市</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="id_district" class="form-label">区/县</label>
                            <select class="form-select" id="id_district" name="district" required>
                                <option value="">请选择区/县</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="id_address" class="form-label">详细地址</label>
                        <input type="text" class="form-control" id="id_address" name="address" placeholder="详细地址，如街道、门牌号等" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="id_phone" class="form-label">联系电话</label>
                            <input type="text" class="form-control" id="id_phone" name="phone" placeholder="手机号码" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="id_zip_code" class="form-label">邮政编码</label>
                            <input type="text" class="form-control" id="id_zip_code" name="zip_code" placeholder="可选">
                        </div>
                    </div>
                    
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="id_is_default" name="is_default">
                        <label class="form-check-label" for="id_is_default">设为默认地址</label>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">保存</button>
                    </div>
                </form>
                
                <script>
                    // 地址表单提交
                    document.getElementById('addressForm').addEventListener('submit', function(event) {
                        event.preventDefault();
                        
                        // 使用FormData获取表单数据
                        const formData = new FormData(this);
                        
                        // 发送AJAX请求
                        fetch(this.action, {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest'
                            }
                        })
                        .then(response => {
                            if (response.ok) {
                                return response.json();
                            }
                            throw new Error('请求失败');
                        })
                        .then(data => {
                            if (data.success) {
                                // 关闭模态框
                                const addressModal = bootstrap.Modal.getInstance(document.getElementById('addressModal'));
                                addressModal.hide();
                                
                                // 刷新地址列表
                                refreshAddressList();
                                
                                // 显示成功消息
                                if (typeof showToast === 'function') {
                                    showToast(data.message || '地址操作成功', 'success');
                                } else {
                                    alert(data.message || '地址操作成功');
                                }
                            } else {
                                if (typeof showToast === 'function') {
                                    showToast(data.message || '操作失败', 'danger');
                                } else {
                                    alert(data.message || '操作失败');
                                }
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            if (typeof showToast === 'function') {
                                showToast('提交失败，请重试', 'danger');
                            } else {
                                alert('提交失败，请重试');
                            }
                        });
                    });
                </script>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'js/area_data_full.js' %}"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化省市区选择器
        initAreaSelector();
        
        // 编辑地址
        initEditAddressButtons();
        
        // 设置默认地址
        initDefaultAddressButtons();
        
        // 删除地址
        initDeleteAddressButtons();
    });
    
    // 初始化编辑地址按钮
    function initEditAddressButtons() {
        const editButtons = document.querySelectorAll('.edit-address');
        editButtons.forEach(button => {
            button.addEventListener('click', function() {
                const addressId = this.dataset.addressId;
                
                // 发送AJAX请求获取地址信息
                fetch(`/users/address/${addressId}/`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // 填充表单
                            document.getElementById('address_id').value = data.address.id;
                            document.getElementById('id_receiver').value = data.address.receiver;
                            document.getElementById('id_address').value = data.address.address;
                            document.getElementById('id_phone').value = data.address.phone;
                            document.getElementById('id_zip_code').value = data.address.zip_code || '';
                            document.getElementById('id_is_default').checked = data.address.is_default;
                            
                            // 设置省市区选择器
                            setAreaSelector(data.address.province, data.address.city, data.address.district, data.address.street);
                            
                            // 更新模态框标题
                            document.getElementById('addressModalLabel').textContent = '编辑地址';
                            
                            // 设置表单提交地址
                            document.getElementById('addressForm').action = `/users/address/${addressId}/edit/`;
                            
                            // 显示模态框
                            const addressModal = new bootstrap.Modal(document.getElementById('addressModal'));
                            addressModal.show();
                        } else {
                            if (typeof showToast === 'function') {
                                showToast('获取地址信息失败', 'danger');
                            } else {
                                alert('获取地址信息失败');
                            }
                        }
                    })
                    .catch(error => {
                        console.error('获取地址信息出错:', error);
                        if (typeof showToast === 'function') {
                            showToast('获取地址信息失败，请重试', 'danger');
                        } else {
                            alert('获取地址信息失败，请重试');
                        }
                    });
            });
        });
    }
    
    // 初始化设置默认地址按钮
    function initDefaultAddressButtons() {
        const defaultButtons = document.querySelectorAll('.set-default-address');
        defaultButtons.forEach(button => {
            button.addEventListener('click', function() {
                const addressId = this.dataset.addressId;
                
                if (confirm('确定要将此地址设为默认地址吗？')) {
                    // 发送AJAX请求设置默认地址
                    fetch(`/users/address/${addressId}/set-default/`, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': getCookie('csrftoken'),
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: new FormData()
                    })
                        .then(response => {
                            if (response.ok) {
                                return response.json();
                            }
                            throw new Error('请求失败');
                        })
                        .then(data => {
                            if (data.success) {
                                // 刷新地址列表而不是刷新整个页面
                                refreshAddressList();
                                
                                if (typeof showToast === 'function') {
                                    showToast(data.message || '默认地址设置成功', 'success');
                                } else {
                                    alert(data.message || '默认地址设置成功');
                                }
                            } else {
                                if (typeof showToast === 'function') {
                                    showToast(data.message || '设置默认地址失败', 'danger');
                                } else {
                                    alert(data.message || '设置默认地址失败');
                                }
                            }
                        })
                        .catch(error => {
                            console.error('设置默认地址出错:', error);
                            if (typeof showToast === 'function') {
                                showToast('设置默认地址失败，请重试', 'danger');
                            } else {
                                alert('设置默认地址失败，请重试');
                            }
                        });
                }
            });
        });
    }
    
    // 初始化删除地址按钮
    function initDeleteAddressButtons() {
        const deleteButtons = document.querySelectorAll('.delete-address');
        deleteButtons.forEach(button => {
            button.addEventListener('click', function() {
                const addressId = this.dataset.addressId;
                
                if (confirm('确定要删除此地址吗？')) {
                    // 发送AJAX请求删除地址
                    fetch(`/users/address/${addressId}/delete/`, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': getCookie('csrftoken'),
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: new FormData()
                    })
                        .then(response => {
                            if (response.ok) {
                                return response.json();
                            }
                            throw new Error('请求失败');
                        })
                        .then(data => {
                            if (data.success) {
                                // 刷新地址列表而不是刷新整个页面
                                refreshAddressList();
                                
                                if (typeof showToast === 'function') {
                                    showToast(data.message || '地址删除成功', 'success');
                                } else {
                                    alert(data.message || '地址删除成功');
                                }
                            } else {
                                if (typeof showToast === 'function') {
                                    showToast(data.message || '删除地址失败', 'danger');
                                } else {
                                    alert(data.message || '删除地址失败');
                                }
                            }
                        })
                        .catch(error => {
                            console.error('删除地址出错:', error);
                            if (typeof showToast === 'function') {
                                showToast('删除地址失败，请重试', 'danger');
                            } else {
                                alert('删除地址失败，请重试');
                            }
                        });
                }
            });
        });
    }
    
    // 刷新地址列表
    function refreshAddressList() {
        fetch('/users/addresses/get/', {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 获取地址列表容器
                const addressTab = document.getElementById('address');
                const addressListContainer = addressTab.querySelector('.address-list');
                
                if (data.addresses.length > 0) {
                    // 如果原来没有地址列表容器，创建一个
                    if (!addressListContainer) {
                        // 清空地址tab内容并创建新的地址列表
                        addressTab.innerHTML = `
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h3>收货地址</h3>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addressModal">
                                    <i class="bi bi-plus-circle"></i> 新增地址
                                </button>
                            </div>
                            <div class="address-list"></div>
                        `;
                    }
                    
                    // 获取新创建的地址列表容器
                    const newAddressListContainer = addressTab.querySelector('.address-list');
                    
                    // 清空当前地址列表
                    newAddressListContainer.innerHTML = '';
                    
                    // 添加新的地址项
                    data.addresses.forEach(address => {
                        const isDefault = address.is_default ? 'default' : '';
                        const defaultBadge = address.is_default ? 
                            '<span class="address-default-badge">默认地址</span>' : '';
                        const defaultButton = address.is_default ? '' : 
                            `<button class="btn btn-sm btn-outline-success set-default-address" data-address-id="${address.id}">
                                设为默认
                            </button>`;
                        const zipCode = address.zip_code ? 
                            `<p class="mb-0 text-muted small">邮编：${address.zip_code}</p>` : '';
                            
                        const addressHtml = `
                            <div class="address-card ${isDefault}">
                                ${defaultBadge}
                                
                                <div class="address-info">
                                    <h6>${address.receiver} <span class="badge bg-light text-dark">${address.phone}</span></h6>
                                    <p class="mb-1">${address.province} ${address.city} ${address.district} ${address.street ? address.street : ''}</p>
                                    <p class="mb-1">${address.address}</p>
                                    ${zipCode}
                                </div>
                                
                                <div class="address-card-actions">
                                    <button class="btn btn-sm btn-outline-primary edit-address" data-address-id="${address.id}">
                                        <i class="bi bi-pencil"></i> 编辑
                                    </button>
                                    ${defaultButton}
                                    <button class="btn btn-sm btn-outline-danger delete-address" data-address-id="${address.id}">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </div>
                            </div>
                        `;
                        
                        newAddressListContainer.insertAdjacentHTML('beforeend', addressHtml);
                    });
                    
                    // 重新绑定事件
                    initEditAddressButtons();
                    initDefaultAddressButtons();
                    initDeleteAddressButtons();
                } else {
                    // 没有地址，显示空状态
                    addressTab.innerHTML = `
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h3>收货地址</h3>
                            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addressModal">
                                <i class="bi bi-plus-circle"></i> 新增地址
                            </button>
                        </div>
                        <div class="text-center py-4">
                            <i class="bi bi-geo-alt" style="font-size: 3rem;"></i>
                            <p class="mt-3">您还没有添加收货地址</p>
                            <button class="btn btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#addressModal">
                                <i class="bi bi-plus-circle"></i> 新增地址
                            </button>
                        </div>
                    `;
                }
            } else {
                if (typeof showToast === 'function') {
                    showToast('获取地址列表失败', 'danger');
                } else {
                    alert('获取地址列表失败');
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
            if (typeof showToast === 'function') {
                showToast('获取地址列表失败，请刷新页面重试', 'danger');
            } else {
                alert('获取地址列表失败，请刷新页面重试');
            }
        });
    }
    
    // 用于获取cookie的函数，用于CSRF保护
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    
    // 重置模态框
    document.getElementById('addressModal').addEventListener('hidden.bs.modal', function() {
        document.getElementById('address_id').value = '';
        document.getElementById('addressForm').reset();
        document.getElementById('addressModalLabel').textContent = '添加新地址';
        document.getElementById('addressForm').action = "{% url 'add_address' %}";
    });
    
    // 初始化省市区选择器
    function initAreaSelector() {
        const provinceSelect = document.getElementById('id_province');
        const citySelect = document.getElementById('id_city');
        const districtSelect = document.getElementById('id_district');
        
        // 检查是否需要创建街道选择框
        let streetSelect = document.getElementById('id_street');
        if (!streetSelect) {
            // 创建街道选择框
            const districtGroup = document.getElementById('id_district').closest('.mb-3');
            if (districtGroup) {
                const streetGroup = document.createElement('div');
                streetGroup.className = 'mb-3';
                streetGroup.innerHTML = `
                    <label for="id_street" class="form-label">街道/乡镇</label>
                    <select class="form-select" id="id_street" name="street">
                        <option value="">请选择街道/乡镇</option>
                    </select>
                `;
                districtGroup.parentNode.insertBefore(streetGroup, districtGroup.nextSibling);
                streetSelect = document.getElementById('id_street');
            }
        }
        
        // 清空所有选择框
        provinceSelect.innerHTML = '<option value="">请选择省份</option>';
        citySelect.innerHTML = '<option value="">请选择城市</option>';
        districtSelect.innerHTML = '<option value="">请选择区/县</option>';
        if (streetSelect) {
            streetSelect.innerHTML = '<option value="">请选择街道/乡镇</option>';
        }
        
        // 加载省份数据
        for (const province in areaData) {
            const option = document.createElement('option');
            option.value = province;
            option.textContent = province;
            provinceSelect.appendChild(option);
        }
        
        // 省份变化时更新城市
        provinceSelect.addEventListener('change', function() {
            // 清空城市和区县下拉框
            citySelect.innerHTML = '<option value="">请选择城市</option>';
            districtSelect.innerHTML = '<option value="">请选择区/县</option>';
            if (streetSelect) {
                streetSelect.innerHTML = '<option value="">请选择街道/乡镇</option>';
            }
            
            const selectedProvince = this.value;
            if (selectedProvince && areaData[selectedProvince]) {
                // 加载选定省份的城市
                for (const city in areaData[selectedProvince]) {
                    const option = document.createElement('option');
                    option.value = city;
                    option.textContent = city;
                    citySelect.appendChild(option);
                }
            }
        });
        
        // 城市变化时更新区县
        citySelect.addEventListener('change', function() {
            // 清空区县下拉框
            districtSelect.innerHTML = '<option value="">请选择区/县</option>';
            if (streetSelect) {
                streetSelect.innerHTML = '<option value="">请选择街道/乡镇</option>';
            }
            
            const selectedProvince = provinceSelect.value;
            const selectedCity = this.value;
            
            if (selectedProvince && selectedCity && 
                areaData[selectedProvince] && 
                areaData[selectedProvince][selectedCity]) {
                // 加载选定城市的区县
                for (const district in areaData[selectedProvince][selectedCity]) {
                    const option = document.createElement('option');
                    option.value = district;
                    option.textContent = district;
                    districtSelect.appendChild(option);
                }
            }
        });
        
        // 区县变化时更新街道
        districtSelect.addEventListener('change', function() {
            if (!streetSelect) return;
            
            // 清空街道下拉框
            streetSelect.innerHTML = '<option value="">请选择街道/乡镇</option>';
            
            const selectedProvince = provinceSelect.value;
            const selectedCity = citySelect.value;
            const selectedDistrict = this.value;
            
            if (selectedProvince && selectedCity && selectedDistrict && 
                areaData[selectedProvince] && 
                areaData[selectedProvince][selectedCity] &&
                areaData[selectedProvince][selectedCity][selectedDistrict]) {
                
                // 加载选定区县的街道
                const streets = areaData[selectedProvince][selectedCity][selectedDistrict];
                if (Array.isArray(streets)) {
                    streets.forEach(street => {
                        const option = document.createElement('option');
                        option.value = street;
                        option.textContent = street;
                        streetSelect.appendChild(option);
                    });
                } else {
                    // 如果是对象，遍历对象的键
                    for (const street in streets) {
                        const option = document.createElement('option');
                        option.value = street;
                        option.textContent = street;
                        streetSelect.appendChild(option);
                    }
                }
            }
        });
    }
    
    // 用于编辑地址时设置省市区选择器的值
    function setAreaSelector(province, city, district, street) {
        const provinceSelect = document.getElementById('id_province');
        const citySelect = document.getElementById('id_city');
        const districtSelect = document.getElementById('id_district');
        const streetSelect = document.getElementById('id_street');
        
        // 创建自定义事件
        const changeEvent = new Event('change', { bubbles: true });
        
        // 设置省份
        if (province) {
            provinceSelect.value = province;
            // 手动触发change事件
            provinceSelect.dispatchEvent(changeEvent);
            
            // 设置城市
            if (city) {
                // 等待城市选项加载完成
                setTimeout(() => {
                    citySelect.value = city;
                    // 手动触发change事件
                    citySelect.dispatchEvent(changeEvent);
                    
                    // 设置区县
                    if (district) {
                        // 等待区县选项加载完成
                        setTimeout(() => {
                            districtSelect.value = district;
                            
                            // 如果有街道选择框和街道值，设置街道
                            if (streetSelect && street) {
                                districtSelect.dispatchEvent(changeEvent);
                                setTimeout(() => {
                                    streetSelect.value = street;
                                }, 100);
                            }
                        }, 100);
                    }
                }, 100);
            }
        }
    }
</script>
{% endblock %} 